package com.jsu.information.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsu.information.mapper.AchievementMapper;
import com.jsu.information.mapper.AchievementTryMapper;
import com.jsu.information.service.AchievementService;
import lombok.extern.slf4j.Slf4j;
import org.example.model.common.enums.RedisCodeEnum;
import org.example.model.information.dto.AchievementDto;
import org.example.model.information.enums.AchievementEnum;
import org.example.model.information.pojo.Achievement;
import org.example.model.information.pojo.AchievementTry;
import org.example.model.common.dtos.ResponseResult;
import org.example.model.common.enums.MailEnum;
import org.example.model.common.enums.WebHttpCodeEnum;
import org.example.utils.common.FileTools;
import org.example.utils.common.Mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class AchievementServiceImpl extends ServiceImpl<AchievementMapper, Achievement> implements AchievementService {
    @Autowired(required = false)
    private Mail mail;
    @Autowired
    private AchievementTryMapper achievementTryMapper;


    /**
     * 返回所有成果集合
     * @return map集合
     */
    @Override
    public ResponseResult getAchievement() {
        List<Achievement> list = getBaseMapper().selectList(null);
        if(list.size()==0||list.isEmpty())
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"暂时没有成果数据");
        List<AchievementDto> dtoList = list.stream()
                .map(AchievementServiceImpl::convertToDto)
                .collect(Collectors.toList());
//        Map<String, List<AchievementDto>> groupedAchievements = dtoList.stream()
//                .collect(Collectors.groupingBy(AchievementDto::getType));
        return ResponseResult.okResult(dtoList);
    }

    private static AchievementDto convertToDto(Achievement achievement) {
        // 创建AchievementDto对象并复制属性
        AchievementDto dto = new AchievementDto();
        dto.setPkId(achievement.getPkId());
        dto.setAchievementName(achievement.getAchievementName());
        dto.setAchievementContent(achievement.getAchievementContent());
        dto.setImage(achievement.getImage());
        dto.setType(achievement.getType());
        dto.setLink(achievement.getLink());

        return dto;
    }

    /**
     * 提交申请试用表
     * @param achievementTry
     * @return
     */
    @Override
    public ResponseResult tryAchievement(AchievementTry achievementTry) {
        achievementTry.setState(AchievementEnum.UN_READ.getNum());
        int count = achievementTryMapper.insert(achievementTry);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"提交失败");
        }
        return ResponseResult.okResult(200,"提交成功");
    }

    /**
     * 管理员端获取所有的试用表
     * @return
     */
    @Override
    public ResponseResult getForm() {
        List<AchievementTry> achievementTries = achievementTryMapper.selectList(null);
        if (achievementTries.size()==0||achievementTries.isEmpty()) {
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"暂时没有申请表");
        }
        return ResponseResult.okResult(achievementTries);
    }

    /**
     * 管理员审批试用表
     * @param achievementTry
     * @return
     */
    @Override
    public ResponseResult checkOneTry(AchievementTry achievementTry) {
        //通过你审批，给对应的用户发邮件
        if (achievementTry.getState().equals(AchievementEnum.PASS.getNum())){
            String email = achievementTry.getEmail();
            //发送短信
            mail.sendMail(email, MailEnum.Through_achievement_trial.getTitle(),MailEnum.Through_achievement_trial.getText());
            //TODO 授权操作等等
        }
        int count = getBaseMapper().update(achievementTry);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"审判失败");
        }
        return ResponseResult.okResult(200,"审批成功");
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @Override
    public ResponseResult uploadExcel(MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"上传的文件不能为空");
        }
        try {
            File excelFile = File.createTempFile("temp", ".xlsx"); // 创建临时文件
            file.transferTo(excelFile); // 将上传的文件保存到临时文件
            List<Achievement> achievements = FileTools.readExcel(excelFile, Achievement.class); // 调用读取 Excel 方法
            //批量导入到数据库
            boolean success = saveBatch(achievements);

            if (success) {
                return ResponseResult.okResult(WebHttpCodeEnum.SUCCESS);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL);
        }
        return ResponseResult.errorResult(WebHttpCodeEnum.FAIL);
    }

    /**
     * 导出文件
     * @param fileName
     * @return
     */
    @Override
    public ResponseResult exportExcel(String fileName) {
        try {
            List<Achievement> achievements = getBaseMapper().selectList(null); // 获取要导出的数据集合
            int count = FileTools.writeExcel(fileName, Achievement.class, achievements);// 调用写入 Excel 方法
            if(count>0)
                return ResponseResult.okResult(count);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"暂时没有数据");
    }

    /**
     * 添加成果
     * @param achievementDto
     * @return
     */
    @Override
    public ResponseResult addAchievement(AchievementDto achievementDto) {
        Achievement achievement = BeanUtil.copyProperties(achievementDto, Achievement.class);
        achievement.setCreateTime(Date.valueOf(LocalDate.now().toString()));
        int count = getBaseMapper().insert(achievement);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"添加失败");
        }
        return ResponseResult.okResult(200,"添加成功");
    }

    /**
     * 删除成果
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteAchievement(int id) {
        int count = getBaseMapper().deleteById(id);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"删除失败");
        }
        return ResponseResult.okResult(200,"删除成功");
    }

    /**
     * 更新成果
     * @param achievementDto
     * @return
     */
    @Override
    public ResponseResult updateAchievement(AchievementDto achievementDto) {
        Achievement achievement = BeanUtil.copyProperties(achievementDto, Achievement.class);
        int count = getBaseMapper().updateById(achievement);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"更新失败");
        }
        return ResponseResult.okResult(200,"更新成功");
    }

    /**
     * 获取试用列表
     * @param id
     * @return
     */
    @Override
    public ResponseResult getTryList(int id) {
        List<AchievementTry> achievementTries = achievementTryMapper.getAchievementTryListByAchievementId(id);
        if (achievementTries.size()==0||achievementTries.isEmpty()) {
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"暂时没有申请表");
        }
        return ResponseResult.okResult(achievementTries);
    }

    /**
     * 搜索成果
     * @param key
     * @return
     */
    @Override
    public ResponseResult searchAchievement(String key) {
        List<Achievement> achievements = getBaseMapper().searchAchievementByKeyword(key);
        if (achievements.size()==0||achievements.isEmpty()) {
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"暂时没有搜索结果");
        }
        List<AchievementDto> achievementDtos = achievements.stream().
                map(AchievementServiceImpl::convertToDto).
                collect(Collectors.toList());
        return ResponseResult.okResult(achievementDtos);
    }

    /**
     * 批量删除成果
     *
     * @param ids
     * @return
     */
    @Override
    public ResponseResult deleteAchievementBatch(int[] ids) {
        List<Integer> idList = java.util.Arrays.stream(ids).boxed().collect(Collectors.toList());
        int count = getBaseMapper().deleteBatchIds(idList);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"批量删除失败");
        }
        return ResponseResult.okResult(200,"批量删除成功");
    }

    /**
     * 获取所有试用列表
     *
     * @return
     */
    @Override
    public ResponseResult getAllTryList() {
        List<AchievementTry> achievementTries = achievementTryMapper.getAchievementTryListWithState();
        if (achievementTries.size()==0||achievementTries.isEmpty()) {
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"暂时没有申请表");
        }
        return ResponseResult.okResult(achievementTries);
    }

}
